import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:wanke/setting_page.dart';
import 'function.dart';
import 'util/event.dart';
import 'login_page.dart';
import 'message_page.dart';
import 'block_page.dart';
import 'top_page.dart';
import 'register_page.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'account_page.dart';

class UserPage extends StatefulWidget {
  @override
  _UserPageState createState() => new _UserPageState();
}

class _UserPageState extends State<UserPage> {
  String uid = "";
  String username = "";
  String nickName = "";
  String avatarUrl;
  bool isLogin = false;
  Color mainColor = Colors.deepOrange;
  Color pickerColor = Color(0xffff5722);
  _UserPageState() {
    setTheme();
    initUser();
    eventBus.on<Event>().listen((event) async {
      if (event.msg == "login") {
        initUser();
      } else if (event.msg == "logout") {
        print("logout");
        this.uid = "";
        this.nickName = "";
        this.isLogin = false;
        removeStorage("uid");
      }
    });
  }
  setTheme() {
    themeColor.then((color) {
      mainColor = color;
      pickerColor = color;
      setState(() {});
    });
  }

  setColor(Color color) {
    setState(() => pickerColor = color);
  }

  initUser() async {
    this.uid = await getStorage("uid");
    if (this.uid != null) {
      var info = await getUserInfo(this.uid);
      if (info == null) {
        return false;
      }
      if (info['code'] == 1) {
        this.nickName = info['msg']['nickname'];
        this.username = info['msg']['username'];
        this.avatarUrl = info['msg']['avatar'];
        this.isLogin = true;
        setState(() {});
      }
    } else {
      this.isLogin = false;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: mainColor,
          border: new Border(bottom: BorderSide.none),
          middle: new Text(
            "我的",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),
          trailing: new CupertinoButton(
            padding: EdgeInsets.all(0.0),
            minSize: 20.0,
            child: new Icon(
              Icons.settings,
              size: 20.0,
            ),
            onPressed: () {
              Navigator.of(context).push(
                new CupertinoPageRoute(builder: (context) {
                  return new SettingPage(mainColor);
                }),
              );
            },
          ),
        ),
        body: new Column(
          children: <Widget>[
            new Container(
              color: mainColor,
              height: 100.0,
              child: new FlatButton(
                padding: EdgeInsets.all(0.0),
                onPressed: () {
                  if (this.isLogin) {
                    Navigator.of(context).push(
                      new CupertinoPageRoute(builder: (context) {
                        return new AccountPage(mainColor);
                      }),
                    ).then((value) {
                      print(value);
                      if (value) {
                        initUser();
                      }
                    });
                  } else {
                    Navigator.of(context).push(
                      new CupertinoPageRoute(builder: (context) {
                        return new LoginPage(mainColor);
                      }),
                    ).then((value) {
                      initUser();
                    });
                  }
                },
                child: new Row(
                  children: <Widget>[
                    new Padding(
                      padding: EdgeInsets.all(10.0),
                      child: new Container(
                        width: 70.0,
                        height: 70.0,
                        decoration: new BoxDecoration(
                          shape: BoxShape.circle,
                        ),
                        child: CircleAvatar(
                          backgroundColor: mainColor,
                          backgroundImage: this.isLogin && this.avatarUrl != null && this.avatarUrl != "" ? new NetworkImage(this.avatarUrl) : AssetImage("images/icon.png"),
                        ),
                      ),
                    ),
                    new SizedBox(
                      width: 5.0,
                    ),
                    this.isLogin
                        ? new Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        new Text(
                          this.nickName ?? this.username,
                          style: new TextStyle(
                            fontSize: 26.0,
                            color: Colors.white,
                          ),
                        ),
                        new SizedBox(
                          height: 8.0,
                        ),
                        new Text(
                          "ID:${this.uid}",
                          style: new TextStyle(
                            fontSize: 16.0,
                            color: new Color(0xFFEEEEEE),
                          ),
                        ),
                      ],
                    )
                        : new Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        new Text(
                          "未登录",
                          style: new TextStyle(
                            fontSize: 26.0,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                    new Expanded(
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          new IconButton(
                            icon: new Icon(
                              Icons.chevron_right,
                              color: Colors.white,
                            ),
                            onPressed: null,
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            new Expanded(
              child: new ListView(
                children: <Widget>[
                  new ListTile(
                    onTap: () async {
                      Clipboard.setData(new ClipboardData(text: "K67kyl63gO"));
                      try {
                        launch("alipays://");
                      } catch (e) {
                        toast("支付宝启动失败，请手动打开支付宝领取红包");
                      }
                    },
                    leading: new ImageIcon(AssetImage("images/redpackage.png")),
                    title: new Text("红包福利"),
                    trailing: new Icon(Icons.chevron_right),
                  ),
                  new Divider(
                    height: 1.0,
                  ),
                  new ListTile(
                    onTap: () {
                      eventBus.fire(new Event("draw"));
                    },
                    leading: new ImageIcon(AssetImage("images/withdraw.png")),
                    title: new Text("一键提币"),
                    trailing: new Icon(Icons.chevron_right),
                  ),
                  new Divider(
                    height: 1.0,
                  ),
                  new ListTile(
                    onTap: () {
                      Navigator.of(context).push(
                        new CupertinoPageRoute(builder: (context) {
                          return new MessagePage(mainColor);
                        }),
                      );
                    },
                    leading: new ImageIcon(
                      AssetImage("images/message.png"),
                    ),
                    title: new Text("消息中心"),
                    trailing: new Icon(Icons.chevron_right),
                  ),
                  new Divider(
                    height: 1.0,
                  ),
                  new ListTile(
                    onTap: () {
                      Navigator.of(context).push(
                        new CupertinoPageRoute(builder: (context) {
                          return new TopPage(mainColor);
                        }),
                      );
                    },
                    leading: new ImageIcon(
                      AssetImage("images/top.png"),
                    ),
                    title: new Text("全网统计"),
                    trailing: new Icon(Icons.chevron_right),
                  ),
                  new Divider(
                    height: 1.0,
                  ),
                  new ListTile(
                    onTap: () {
                      Navigator.of(context).push(
                        new CupertinoPageRoute(builder: (context) {
                          return new BlockPage(mainColor);
                        }),
                      );
                    },
                    leading: new ImageIcon(AssetImage("images/trade.png")),
                    title: new Text("区块查询"),
                    trailing: new Icon(Icons.chevron_right),
                  ),
                  new Divider(
                    height: 1.0,
                  ),
                  new ListTile(
                    onTap: () {
                      Navigator.of(context).push(
                        new CupertinoPageRoute(builder: (context) {
                          return new RegisterPage(mainColor);
                        }),
                      ).then((value) {
                        if (value != null && value > 0) {
                          eventBus.fire(new Event("register"));
                        }
                      });
                    },
                    leading: new Icon(Icons.person_add),
                    title: new Text("注册账号"),
                    trailing: new Icon(Icons.chevron_right),
                  ),
                  new Divider(
                    height: 1.0,
                  ),
                  new ListTile(
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            title: const Text('设置主题颜色'),
                            content: SingleChildScrollView(
                              child: new ColorPicker(
                                pickerColor: pickerColor,
                                onColorChanged: setColor,
                                colorPickerWidth: 1000.0,
                                pickerAreaHeightPercent: 0.8,
                                enableLabel: false,
                                enableAlpha: false,
                              ),
                            ),
                            actions: <Widget>[
                              FlatButton(
                                child: Text('默认'),
                                onPressed: () {
                                  mainColor = Color(0xffff5722);
                                  pickerColor = Color(0xffff5722);
                                  setStorage("themeColor", pickerColor.value.toString());
                                  eventBus.fire(new Event("theme"));
                                  setState(() {});
                                  Navigator.of(context).pop();
                                },
                              ),
                              FlatButton(
                                child: Text('确定'),
                                onPressed: () {
                                  if (pickerColor.alpha != 0xFF) {
                                    toast("暂不支持设置透明度，请重新选择");
                                    return;
                                  }
                                  setStorage("themeColor", pickerColor.value.toString());
                                  mainColor = pickerColor;
                                  eventBus.fire(new Event("theme"));
                                  setState(() {});
                                  Navigator.of(context).pop();
                                },
                              ),
                              FlatButton(
                                child: Text('取消'),
                                onPressed: () {
                                  pickerColor = mainColor;
                                  setState(() {});
                                  Navigator.of(context).pop();
                                },
                              ),
                            ],
                          );
                        },
                      );
                    },
                    leading: new ImageIcon(
                      AssetImage("images/theme.png"),
                    ),
                    title: new Text("主题颜色"),
                    trailing: new Icon(Icons.chevron_right),
                  ),
                  new Divider(
                    height: 1.0,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
